package com.dingtalk;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dingtalkim_1_0.Client;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardHeaders;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiImChatScencegroupInteractivecardCallbackRegisterRequest;
import com.dingtalk.api.request.OapiImChatScencegroupMessageSendV2Request;
import com.dingtalk.api.response.OapiImChatScencegroupInteractivecardCallbackRegisterResponse;
import com.dingtalk.api.response.OapiImChatScencegroupMessageSendV2Response;
import com.dingtalk.constant.AppConstant;
import com.dingtalk.constant.UrlConstant;
import com.taobao.api.ApiException;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.dingtalk.util.AccessTokenUtil.getAccessToken;

/**
 * 实现了机器人的简单问答功能
 */
@RestController
@RequestMapping(value = "/robots")
public class RobotsController {

    private static final String cardMSG = "忘记密码";

    @RequestMapping(value = "/robots1")
    public String helloRobots(@RequestBody(required = false) JSONObject json
    ) {
        System.out.println(json);
        String content = json.getJSONObject("text").get("content").toString().replaceAll(" ", "");
        if (cardMSG.contains(content)) {
            // 发送官方测试模板
//            return actionCardMsg();
            // 参数准备
            String outTrackId = String.valueOf(System.currentTimeMillis() / 1000);
            Map<String, String> cardDataCardParamMap = new HashMap<>();
            cardDataCardParamMap.put("title", "www.baidu.com");
            cardDataCardParamMap.put("content", "用户无法登录");
            cardDataCardParamMap.put("date", "重置密码");
            cardDataCardParamMap.put("like", "磁盘存储空间已满");
            cardDataCardParamMap.put("node", "无法从启服务");
            cardDataCardParamMap.put("url", "https://www.yuque.com/rimutuyuan-ra0uj/fwq5rk/eo3iwn");
            Map<String, String> cardDataCardMediaIdParamMap = new HashMap<>();

            // 发送互动卡片消息
//            return sendInteractiveCardMessage(outTrackId, cardDataCardParamMap, cardDataCardMediaIdParamMap);
        }
        return learning();
    }

//    public String sendInteractiveCardMessage(String outTrackId, Map<String, String> cardDataCardParamMap, Map<String, String> cardDataCardMediaIdParamMap) {
//        try {
//            Client client = RobotsController.createClient();
//            SendInteractiveCardHeaders sendInteractiveCardHeaders = new SendInteractiveCardHeaders();
//            sendInteractiveCardHeaders.xAcsDingtalkAccessToken = getAccessToken();
//            SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = new SendInteractiveCardRequest.SendInteractiveCardRequestCardData()
//                    .setCardMediaIdParamMap(cardDataCardMediaIdParamMap)
//                    .setCardParamMap(cardDataCardParamMap);
//            SendInteractiveCardRequest sendInteractiveCardRequest = new SendInteractiveCardRequest()
//                    .setCardTemplateId(AppConstant.CARD_TEMPLATE_ID)
//                    .setOpenConversationId(AppConstant.OPEN_CONVERSATION_ID)
//                    .setOutTrackId(outTrackId)
//                    .setRobotCode(AppConstant.ROBOT_CODE)
//                    .setConversationType(1)
//                    .setCallbackRouteKey("dingding")
//                    .setCardData(cardData);
//            SendInteractiveCardResponse rsp = client.sendInteractiveCardWithOptions(sendInteractiveCardRequest, sendInteractiveCardHeaders, new RuntimeOptions());
//            return "success";
////            sendToWebHook("互动卡片消息发送成功", ApiUrlConstant.WEB_HOOK_TEST);
//        } catch (Exception e) {
//
//            System.out.println("互动卡片消息发送失败" + e);
//            return "fail";
////            logger.error("互动卡片消息发送失败", e);
////            sendToWebHook("互动卡片消息发送失败，请查看日志", ApiUrlConstant.WEB_HOOK_TEST);
//        }
//
//    }

    /**
     * 使用 Token 初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dingtalkim_1_0.Client createClient() throws Exception {
        Config config = new Config();
        config.protocol = "https";
        config.regionId = "central";
        return new com.aliyun.dingtalkim_1_0.Client(config);
    }


    @PostMapping(value = "/callback")
    @ResponseBody
    public void callBack(String type, HttpServletRequest req) {
        System.out.println(req);
        System.out.println(type);
    }

    public void interactiveCardRegisterCallBack(String callBackUrl) {
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/im/chat/scencegroup/interactivecard/callback/register");
            OapiImChatScencegroupInteractivecardCallbackRegisterRequest req = new OapiImChatScencegroupInteractivecardCallbackRegisterRequest();
            req.setCallbackUrl(callBackUrl);
            OapiImChatScencegroupInteractivecardCallbackRegisterResponse registerRespone = client.execute(req, getAccessToken());
            if (registerRespone.isSuccess()) {
                System.out.println("互动卡片回调注册成功！");
//                logger.info("互动卡片回调注册成功！");
            } else {
                System.out.println("互动卡片回调注册失败，原因:" + registerRespone.getErrmsg());
//                logger.info("互动卡片回调注册失败，原因:" + registerRespone.getErrmsg());
            }
        } catch (ApiException e) {
            System.out.println("互动卡片回调注册失败，原因是：" + e.getErrMsg());
//            logger.info("互动卡片回调注册失败，原因是：" + e.getErrMsg());
        }
    }

    /**
     * 直接回复文本消息
     */
    private String learning() {

        return "{" +
                "    \"text\": {" +
                "        \"content\": \"我就是我, 是不一样的烟火\"" +
                "    }," +
                "    \"msgtype\": \"text\"" +
                "}";
    }



}
